package com.itheima.day1;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;

// 函数对象好处2：延迟执行
public class Sample7 {
    static Logger logger = init(Level.DEBUG);
//    static Logger logger = init(Level.INFO);

    public static void main(String[] args) {
        /*if (logger.isDebugEnabled()) {
            logger.debug("{}", expensive());
        }*/

        logger.debug("{}", expensive());        // expensive() 立刻执行（无论是否输出日志，都会消耗资源）

        logger.debug("{}", () -> expensive());  // 函数对象使得 expensive 延迟执行（仅当日志级别为DUBUG时执行，避免不必要的计算）

    }

    static String expensive() {
        System.out.println("执行耗时操作...");
        return "日志";
    }

    static Logger init(Level level) {
        // 1. 创建配置构造器
        ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder()
                .setStatusLevel(Level.ERROR)
                .setConfigurationName("BuilderTest");

        // 2. 配置控制台输出（格式、目标）
        AppenderComponentBuilder appender = builder.newAppender("Stdout", "CONSOLE")
                        .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT)
                        .add(builder.newLayout("PatternLayout")
                                .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));

        // 3. 将配置应用到根日志级别
        builder.add(appender)
                .add(builder.newRootLogger(level).add(builder.newAppenderRef("Stdout")));

        // 4. 初始化Log4j配置
        Configurator.initialize(builder.build());
        return LogManager.getLogger();
    }
}
